package ssi.staaar;

import java.util.ArrayList;

import ssi.peeno.model.Message;
import ssi.staar.R;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.OnTabChangeListener;

public class MessageListActivity extends TabActivity {
	private LocationManager locManager;
	private LocationListener locListener;
    private long minTime;
    private float minMeters;
    private float radiusMeters;
    private ArrayAdapter<Message> messagePublicList;
    private ArrayAdapter<Message> messagePrivateList;
    private int currentList;
	private double currentLat;
	private double currentLong;
	private double currentAlt;
	private static ArrayList<Message> currentPublicMessages;
	private static ArrayList<Message> currentPrivateMessages;
	private static boolean gpsEnabled;
	private final Handler msgListDownloadHandler = new Handler(); //handler which manage modification for updatemsglist
	private final Runnable updateThread = new Runnable() {	
		@Override
		public void run() {
			updatePrivateMessageList();
			updatePublicMessageList();
		}
	}; //thread which update msglists in gui
	private Location currentLocation;
	
	public static ArrayList<Message> getPrivateMessageList() {
		return currentPrivateMessages;
	}

	public static ArrayList<Message> getPublicMessageList() {
		return currentPublicMessages;
	}

	private void checkForNotification() {
		Staaar.stControl.checkNotification();
	}

	private void CreateMenu(Menu menu) {
		menu.setQwertyMode(true);
		MenuItem menu1 = menu.add(0, 0, 0, "Settings");
		{
			menu1.setIcon(R.drawable.settings);
		}
		MenuItem menu2 = menu.add(0, 1, 1, "Logout");
		{
			menu2.setIcon(R.drawable.logout);
		}
	}

	public static boolean isGpsEnabled() {
		return gpsEnabled;
	}
	
	public void goToAddMessageActivity(View view) {
		Intent iAddMessage = new Intent();
		iAddMessage.setClass(getApplicationContext(), AddMessageActivity.class);
		startActivity(iAddMessage);
	}

	public void goToAugmentedRealityActivity(View view) {
		Intent iAR = new Intent();
		iAR.setClass(getApplicationContext(), ARActivity.class);
		iAR.putExtra("currentLat", currentLat);
		iAR.putExtra("currentLong", currentLong);
		iAR.putExtra("currentAlt", currentAlt);
		startActivity(iAR);
	}

	public void goToManageFriendsActivity(View view) {
		Intent iFriends = new Intent();
		iFriends.setClass(getApplicationContext(), ManageFriendsActivity.class);
		startActivity(iFriends);
	}

	private void logout() {
		Staaar.stControl.logout();
		Log.d("[STAAAR]", "logging out");
		finish();
	}

	private boolean MenuChoice(MenuItem item) {
		switch(item.getItemId()){
			case 0:
				Intent iSet = new Intent();
				iSet.setClass(getApplicationContext(), SettingsActivity.class);
				startActivity(iSet);
	            return true;
			case 1:
				logout();
	            return true;
		}
		return false;
	}

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
		setContentView(R.layout.messages);
		TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);
		mTabHost.addTab(mTabHost.newTabSpec("publicMessage").setIndicator("Public").setContent(R.id.publicMessageList));
	    mTabHost.addTab(mTabHost.newTabSpec("privateMessage").setIndicator("Private").setContent(R.id.privateMessageList));
	    mTabHost.setCurrentTab(0);
	    currentList = R.id.publicMessageList;
	    mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				System.out.println(tabId);	
				if(tabId.equalsIgnoreCase("publicMessage")) {
					currentList = R.id.publicMessageList;
				}
				if(tabId.equalsIgnoreCase("privateMessage")) {
					currentList = R.id.privateMessageList;
				}
			}
		});
		locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locListener = new LocationListener() {
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
			}
			
			@Override
			public void onProviderEnabled(String provider) {				
			}
			
			@Override
			public void onProviderDisabled(String provider) {
			}
			
			@Override
			public void onLocationChanged(Location location) {
				updateMessageList(location);
			}
		};
		startLocationUpdates();
		checkForNotification();
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		CreateMenu(menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	     return MenuChoice(item);    
	}

	public void onPause() {
		super.onPause();
		currentList = 3;
		stopLocationUpdates();
	}

	protected void onResume() {
		super.onResume();
		restartLocationUpdates();
		SharedPreferences pref = getSharedPreferences(Staaar.PREFS_NAME, 0);
		minMeters = pref.getFloat("MinMeters", Staaar.DEFAULT_METERS);
		minTime = pref.getLong("MinMinutes", Staaar.DEFAULT_MINUTES);
		radiusMeters = pref.getFloat("RadiusMeters", Staaar.DEFAULT_RADIUS_METERS);
		Log.d("[STAAAR]", "MinMeters: " + minMeters);
		Log.d("[STAAAR]", "MinMinutes: " + minTime);
		Log.d("[STAAAR]", "RadiusMeters: " + radiusMeters);
	}

	protected void onStop() {
		super.onStop();
		stopLocationUpdates();
	}

	private void readMessage(Message item) {
	    Intent iReadMessage = new Intent();
	    iReadMessage.putExtra("Message.Current", item);
	    iReadMessage.setClass(getApplicationContext(), ReadMessageActivity.class);
	    startActivity(iReadMessage);
	}

	private void restartLocationUpdates() {
		Log.d("[STAAAR]", "Restarting location updates");
		if (locManager != null && locListener != null) {
			locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime, minMeters, locListener);
			locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minMeters, locListener);
		}
	}

	private void startLocationUpdates() {
		Log.d("[STAAAR]", "Starting location updates");
		locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime, minMeters, locListener);
		locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minMeters, locListener);
	}

	private void stopLocationUpdates() {
		Log.d("[STAAAR]", "Stopping location updates");
		if (locManager != null && locListener != null)
			locManager.removeUpdates(locListener);
	}
	
	/**
	 * Start a thread that download public and private messagelist, at the end of download 
	 * launch the update thread to update the gui
	 * @param location
	 */
	private void updateMessageList(Location location) {
		gpsEnabled = (!locManager.getProviders(true).isEmpty());
		currentLat = location.getLatitude();
		currentLong = location.getLongitude();
		currentAlt = location.getAltitude();
		currentLocation = location;
		Thread giantThread = new Thread() {
			@Override
			public void run() {
				currentPrivateMessages = Staaar.stControl.requestMessageList(currentLocation.getLatitude(), currentLocation.getLongitude(), radiusMeters, 2);
				currentPublicMessages = Staaar.stControl.requestMessageList(currentLocation.getLatitude(), currentLocation.getLongitude(), radiusMeters, 1);
				msgListDownloadHandler.post(updateThread);
			}		
		};
		giantThread.start();
	}

	/**
	 * Update private message list tab
	 */
	private void updatePrivateMessageList() {
		messagePrivateList = new ArrayAdapter<Message>(this, R.layout.friend_list_item, currentPrivateMessages);
		ListView listview = (ListView)findViewById(R.id.privateMessageList);
		listview.setAdapter(messagePrivateList);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				readMessage(messagePrivateList.getItem(arg2));
			}   	
		});
	}

	/**
	 * Update public message list tab
	 */
	private void updatePublicMessageList() {  
	    messagePublicList = new ArrayAdapter<Message>(this, R.layout.friend_list_item, currentPublicMessages);
        ListView listview = (ListView)findViewById(R.id.publicMessageList);
        listview.setAdapter(messagePublicList);
        listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				readMessage(messagePublicList.getItem(arg2));
			}   	
		});
	}
}
